from django.shortcuts import render, HttpResponse, redirect
from django.conf import settings


def permission_initial(current_user, request):
    """
    :param current_user: model object
    :param request: request
    :return:
    """
    if not current_user:
        return render(request, 'app_main/login.html', {'msg': '用户名或密码错误'})
    else:
        p_list = current_user.roles.filter(permissions__isnull=False).values('permissions__id',
                                                                             'permissions__title',
                                                                             'permissions__name',
                                                                             'permissions__p__title',
                                                                             'permissions__p__url',
                                                                             'permissions__menu_id',
                                                                             'permissions__menu__title',
                                                                             'permissions__menu__icon',
                                                                             'permissions__url').distinct()
        permission_dict = {}
        menu_dict = {}

        for item in p_list:
            dic = {'title': item['permissions__title'], 'url': item['permissions__url'],
                   'p_title': item['permissions__p__title'], 'p_url': item['permissions__p__url']
                   }
            permission_dict[item['permissions__name']] = dic
            if item['permissions__menu_id']:
                if item['permissions__menu_id'] not in menu_dict:
                    menu_dict[item['permissions__menu_id']] = {
                        'title': item['permissions__menu__title'],
                        'icon': item['permissions__menu__icon'],
                        'children': [{'title': item['permissions__title'], 'url': item['permissions__url']}]
                    }
                else:
                    menu_dict[item['permissions__menu_id']]['children'].append({'title': item['permissions__title'],
                                                                                 'url': item['permissions__url']})

        request.session[settings.SESSION_PERMISSION_KEY] = permission_dict
        request.session[settings.SESSION_MENU_KEY] = menu_dict

        return redirect('/')
